const fs = require('fs')
const path = require('path')
const { linuxCopy } = require('../utils/copy')
const xSpinner = require('../utils/ora')()


function replaceWord(file, target, value) {
    let reg = eval(`/${target}/g`)
    let rewrite = false
    let data = fs.readFileSync(file, 'utf-8')
    if (data) {
        if (data.match(reg)) {
            rewrite = true
            // console.log('rewrite file:', rewrite, file)
            data = data.replace(reg, value)
        }
    } else {
        console.log('file no data:', file)
    }
    return {
        data,
        rewrite
    }
}

function printDirFiles(filepath, isFileCb = null) {
    fs.readdir(filepath, function(err, files) {
        if (err) {
            return console.error(err)
        }

        //遍历目录下的所有文件
        files.forEach(function(file) {
            let firDir = path.join(filepath, file); //获取当前文件绝对路径 
            // console.log('current file path:', firDir)
            fs.stat(firDir, function(err, stats) {
                if (err) {
                    console.warn('获取文件stats失败')
                } else {
                    if (stats.isFile()) {
                        isFileCb && isFileCb(firDir)
                    } else if (stats.isDirectory()) {
                        printDirFiles(firDir) //递归遍历
                    }
                }
            })
        })
    })
}

function makeDir(dir) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
        console.log('The ' + dir + ' folder has been created!');
    }
}


function generateNpmPackageTemp(packageName, outPath) {
    console.log('🚗 🚕 🚒 🚌  generate npm package template ...... \n')
    xSpinner.start()

    let tmpPath = path.join(__dirname, '../', 'templates/npmpackage.tpl/')
    // let toRootPath = path.join(__dirname, '../', 'tmp'); //for test
    // makeDir(toRootPath); //for 
    // let toFilePath = path.join(__dirname, '../', `tmp/${packageName}/`); //for test
    
    let toFilePath = path.join(outPath, `/${packageName}/`); //for production

    makeDir(toFilePath)

    // step1 复制项目
    linuxCopy(tmpPath, toFilePath)

    let replaceFileKeyword = function(filePath) {
        const { data, rewrite } = replaceWord(filePath, '{{packagename}}', packageName)
        if (rewrite) {
            fs.writeFileSync(filePath, data)
        }
    }

    setTimeout(() => {
        // step2 替换关键字
        printDirFiles(toFilePath, replaceFileKeyword)

        xSpinner.stop()

        console.log('\ncreate npm package [%s] done!', packageName)
    }, 2000);
}

module.exports = generateNpmPackageTemp